﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MessageCallAspect.Inspector.MessageSink;
using MessageCallAspect.Inspector;
using MessageCallAspect.Aspect.Cache;
using MessageCallAspect.Aspect.Log;

namespace MessageCallAspect
{
    public class InspectorModuleContext: ModuleContext
    {
        #region fields

        private readonly List<IMessageSinkCreator> m_SharedMessageSinkCreators;

        #endregion

        #region ctor

        public InspectorModuleContext()
        {
            m_SharedMessageSinkCreators = InitializeSharedMessageSinkCreators();
            InitializeServices();
        }

        #endregion

        /// <summary>
        /// enableInspectors by default is true
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serviceInstance"></param>
        public override void AddService<T>(T serviceInstance)
        {
            AddService<T>(serviceInstance,true, null);
        }

        public void AddService<T>(T serviceInstance, bool enableInspectors, params IMessageSinkCreator[] messageSinkCreators)
            where T : class
        {
            if (enableInspectors)
            {
                IEnumerable<IMessageSinkCreator> sharedMessageSinkCreators;
                if (messageSinkCreators != null)
                {
                    sharedMessageSinkCreators = m_SharedMessageSinkCreators.Union(messageSinkCreators);
                }
                else 
                {
                    sharedMessageSinkCreators = m_SharedMessageSinkCreators;
                }
                base.AddService(serviceInstance.InspectorProxy(this, sharedMessageSinkCreators.ToArray()));
            }
            else
            {
                base.AddService<T>(serviceInstance);
            }
            
        }


        protected virtual List<IMessageSinkCreator> InitializeSharedMessageSinkCreators()
        {
            return new List<IMessageSinkCreator> 
            {
                new LogMessageSinkCreator{ Order = int.MinValue}
            };
        }

        protected virtual void InitializeServices()
        {
            this.AddService<ICacheProvider>(new MemoryCacheProvider(),false);
        }
    }
}
